//
//  WJMainTabViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/18.
//

import UIKit
import SnapKit
import MobileCoreServices
import Photos

class WJMainTabViewController: UIViewController {

    var customTabBar = WJMainTabBarView()
    private var currentViewController: UIViewController?
    
    lazy var imagePicker: UIImagePickerController = {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
        imagePicker.mediaTypes = [UTType.image.identifier]
        return imagePicker
    }()
    
    private let viewControllers: [UIViewController] = [
        WJNavigationController(rootViewController: WJHomeViewController()),
        WJNavigationController(rootViewController: UIViewController()),
        WJNavigationController(rootViewController: WJMineViewController())
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupCustomTabBar()
        setupViewControllers()
    }
    
    private func setupCustomTabBar() {
        customTabBar.layer.masksToBounds = true
        customTabBar.layer.cornerRadius = tabBarHeight / 2.0
        customTabBar.delegate = self
        customTabBar.itemTitles = ["Home", "", "Mine"]
        customTabBar.normalColor = UIColor(hex: "#121212").withAlphaComponent(0.3)
        customTabBar.selectedColor = UIColor(hex: "#121212")
        customTabBar.itemIcons = [
            UIImage(named: "home_icon_normal")!,
            UIImage(named: "add_icon")!,
            UIImage(named: "mine_icon_normal")!,
        ]
        customTabBar.selectedItemIcons = [
            UIImage(named: "home_icon_selected")!,
            UIImage(named: "add_icon")!,
            UIImage(named: "mine_icon_selected")!,
        ]
        
        view.addSubview(customTabBar)
        let image = UIImage(named: "main_tab_bg")
        var aspectRatio = 1.0
        if let image = image {
            aspectRatio = image.aspectRatioOfWH()
        }
        customTabBar.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-safeAreaBottom)
            make.centerX.equalToSuperview()
            make.height.equalTo(tabBarHeight)
            make.width.equalTo(tabBarHeight * aspectRatio)
        }
        customTabBar.barHeight = tabBarHeight
    }
    
    func setCustomTabBarHidden(_ hidden: Bool) {
        customTabBar.isHidden = hidden
    }
    
    private func setupViewControllers() {
        // 初始显示第一个视图控制器
        changeViewController(to: 0)
    }
    
    func changeViewController(to index: Int) {
        // 移除当前显示的视图控制器
        currentViewController?.willMove(toParent: nil)
        currentViewController?.view.removeFromSuperview()
        currentViewController?.removeFromParent()
        
        // 添加新的视图控制器
        let newVC = viewControllers[index]
        addChild(newVC)
        view.insertSubview(newVC.view, belowSubview: customTabBar)
        newVC.view.frame = view.bounds
        newVC.didMove(toParent: self)
        customTabBar.selectedIndex = index
        
        currentViewController = newVC
    }
}

extension WJMainTabViewController: WJMainTabBarViewDelegate {
    func mainTabBarDidSelectAddButton(_ tabBar: WJMainTabBarView) {
        showBottomPopup()
    }
    
    func mainTabBar(_ tabBar: WJMainTabBarView, didSelectItemAt index: Int) {
        changeViewController(to: index)
    }
    
    private func showBottomPopup() {
        let popupView = WJAddPDFPopupView()
        popupView.delegate = self
        WJPopupManager.shared.showCustomPopup(popupView)
    }
}

extension WJMainTabViewController: WJAddPDFPopupViewDelegate {
    func didClickCameraItem(_ popupView: WJAddPDFPopupView) {
        WJPermissionManager.shared.prepareForCameraUsage(in: self) { [weak self] granted in
            guard let self = self else { return }
            let cameraVC = WJCameraViewController()
            cameraVC.modalPresentationStyle = .fullScreen
            present(cameraVC, animated: true)
        }
    }
    
    func didClickGalleryItem(_ popupView: WJAddPDFPopupView) {
        WJPermissionManager.shared.prepareForPhotoLibraryUsage(in: self) { [weak self] granted in
            guard let self = self else { return }
            openPhotos()
        }
    }
    
    func didClickFilesItem(_ popupView: WJAddPDFPopupView) {
        openDocumentPicker()
    }
}

extension WJMainTabViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func openPhotos() {
        present(imagePicker, animated: true)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        dismiss(animated: true) 
        // 获取选中的图片
        if let image = info[.originalImage] as? UIImage {
            // 处理选中的图片
            handleSelectedImage(image)
        } else if let image = info[.editedImage] as? UIImage {
            // 如果允许编辑，处理编辑后的图片
            handleSelectedImage(image)
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true)
    }
    
    private func handleSelectedImage(_ image: UIImage) {
        WJProgressHUD.showLoading()
        WJPdfGenerator.createPDFAndSaveToDatabase(from: [image], open: true) { success in
            if !success {
                WJProgressHUD.showInfo(with: "Failed")
            }
            WJProgressHUD.dismiss()
        }
    }
}

extension WJMainTabViewController: UIDocumentPickerDelegate {
    func openDocumentPicker() {
        // 使用现代的 UTType 方式
        if #available(iOS 14.0, *) {
            let documentPicker = UIDocumentPickerViewController(
                forOpeningContentTypes: [.pdf],
                asCopy: true // 重要：设置为拷贝模式
            )
            documentPicker.delegate = self
            documentPicker.allowsMultipleSelection = false
            
            // iPad 适配
            if let popover = documentPicker.popoverPresentationController {
                popover.sourceView = self.view
                popover.sourceRect = CGRect(x: self.view.bounds.midX,
                                          y: self.view.bounds.midY,
                                          width: 0, height: 0)
                popover.permittedArrowDirections = []
            }
            UINavigationBar.appearance().tintColor = nil // 或使用系统默认蓝色
            UINavigationBar.appearance().titleTextAttributes = nil
            present(documentPicker, animated: true) { [weak self] in
                guard let _ = self else { return }
                UINavigationBar.appearance().tintColor = .systemBlue
            }
        } else {
            // iOS 14 以下的备用方案
            let documentPicker = UIDocumentPickerViewController(
                documentTypes: [kUTTypePDF as String],
                in: .import
            )
            documentPicker.delegate = self
            documentPicker.allowsMultipleSelection = true
            
            present(documentPicker, animated: true)
        }
    }
    
    // 文档选择完成后调用
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let selectedURL = urls.first else {
            WJProgressHUD.showInfo(with: "Please select at least one file")
            return
        }
        
        // 检查是否是PDF文件
        if selectedURL.pathExtension.lowercased() == "pdf" {
            WJPDFFilesImportTool.handlePDFImport(at: selectedURL)
        } else {
            WJProgressHUD.showInfo(with: "Please select the file in PDF format")
        }
    }
    
    // 文档选择被取消时调用
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
//        print("文件选择已取消")
    }
}
